#!/bin/bash
set -e -x

cd $(dirname $0)/..

. ./hack/version.sh

GO=${GO-go}

for i in crictl kubectl k8e-agent k8e-server k8e-token k8e-etcd-snapshot k8e-secrets-encrypt k8e-certificate k8e-completion; do
rm -f bin/$i${BINARY_POSTFIX}
    ln -s k8e${BINARY_POSTFIX} bin/$i${BINARY_POSTFIX}
done

cp contrib/util/check-config.sh bin/check-config
cp contrib/util/init-os-config.sh bin/init-os-config

rm -rf build/data
mkdir -p build/data build/out
mkdir -p dist/artifacts
mkdir -p ./etc

(
    set +x
    cd bin
    find . -not -path '*/\.*' -type f -exec sha256sum {} \; | sed -e 's| \./| |' | sort -k2 >.sha256sums
    (
        for f in $(find . -type l); do
            echo $f $(readlink $f)
        done
    ) | sed -e 's|^\./||' | sort >.links
    set -x
)

tar cvf ./build/out/data.tar ./bin
zstd --no-progress -T0 -16 -f --long=25 --rm ./build/out/data.tar -o ./build/out/data.tar.zst
HASH=$(sha256sum ./build/out/data.tar.zst | awk '{print $1}')

cp ./build/out/data.tar.zst ./build/data/${HASH}.tar.zst

BIN_SUFFIX="-${ARCH}"
if [ ${ARCH} = amd64 ]; then
    BIN_SUFFIX=""
elif [ ${ARCH} = aarch64 ] || [ ${ARCH} = arm64 ]; then
    BIN_SUFFIX="-arm64"
fi

CMD_NAME=dist/artifacts/k8e${BIN_SUFFIX}${BINARY_POSTFIX}

GOOS=linux CC=gcc CXX=g++ "${GO}" generate
LDFLAGS="
    -X github.com/xiaods/k8e/pkg/version.Version=$VERSION
    -X github.com/xiaods/k8e/pkg/version.GitCommit=${COMMIT:0:8}
    -w -s
"
TAGS="urfave_cli_no_docs"
STATIC="-extldflags '-static'"
CGO_ENABLED=0 "${GO}" build -tags "$TAGS" -buildvcs=false -ldflags "$LDFLAGS $STATIC" -o ${CMD_NAME} ./cmd/k8e

stat ${CMD_NAME}

echo ${CMD_NAME} ${COMMIT}